package com.efounder.chat.fragment;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.form.application.ApplicationContainer;
import com.efounder.form.application.FormApplication;
import com.efounder.form.application.FormViewContainer;
import com.efounder.form.application.util.Form;
import com.efounder.form.application.util.FormAppUtil;
import com.efounder.form.builder.XML2Forms;
import com.efounder.frame.ViewSize;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.frame.title.EFTitleView;
import com.efounder.frame.title.EFTitleViewUtils;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.xmlparse.EFAppAccountRegistry;
import com.efounder.frame.xmlparse.EFXmlConstants;
import com.efounder.mobilemanager.R;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * Created by hudq on 2016/8/29. xx
 * 处理一个表单，用此类（区别于 {@link EFAppAccountFormListFragment}）
 */

public class EFAppAccountFormFragment extends EFFragment {

    private static final String TAG = "EFAppAccountFormFragment";

    private int position;
    private StubObject stubObject;

    private Handler handler = new MyHandler(this);
    //    private ProgressDialog progressDialog;//使用showRightProgressBar代替
    private LinearLayout rootLayout;

    private ApplicationContainer applicationContainer;

    private static class MyHandler extends Handler {
        WeakReference<EFAppAccountFormFragment> weakReference;

        public MyHandler(EFAppAccountFormFragment fragment) {
            this.weakReference = new WeakReference<EFAppAccountFormFragment>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            EFAppAccountFormFragment fragment = weakReference.get();
            if (fragment == null) return;
            switch (msg.what) {
                case 1:
//                    fragment.progressDialog.dismiss();
                    //添加当前Form
                    fragment.addForm(fragment.rootLayout, fragment.applicationContainer);
                    break;
            }
        }
    }

    public static EFAppAccountFormFragment newInstance(int position, StubObject stubObject) {
        EFAppAccountFormFragment appAccountFragment = new EFAppAccountFormFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putSerializable("stubObject", stubObject);
        appAccountFragment.setArguments(bundle);
        return appAccountFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        position = getArguments().getInt("position");
        stubObject = (StubObject) getArguments().getSerializable("stubObject");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.ef_fragment_app_account_form, container, false);
        TextView textView = (TextView) view.findViewById(R.id.textView_test);
//        textView.setText(position+"--" + stubObject.getCaption() +"--"+ stubObject.getString(EFXmlConstants.ATTR_FORM,""));

        rootLayout = (LinearLayout) view.findViewById(R.id.rootLayout);

        rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    rootLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

                addForm(rootLayout);
            }

        });


        return view;
    }


    private void addForm(LinearLayout ll) {
        //1.attachForm
        String attachForm = stubObject.getString(EFXmlConstants.ATTR_ATTACH_FORM, "");
        if ("".equals(attachForm)) {
            //TODO 1.生成 form--ApplicationContainer（线程中） 2.添加 FormViewContainer 到界面
//            progressDialog = new ProgressDialog(getActivity());
//            progressDialog.setMessage("正在生成表单...");
//            progressDialog.show();//使用showRightProgressBar代替
            EFTitleView titleView = EFTitleViewUtils.getEFTitleView(EFAppAccountFormFragment.this);
            if (titleView != null) {
                titleView.showRightProgressBar();
            }
            final Runnable runnable = new Runnable() {

                @Override
                public void run() {
                    applicationContainer = generateOneForm(rootLayout);
                }
            };
            new Thread() {
                @Override
                public void run() {
                    super.run();
//                    if (Looper.myLooper() == null){
                    Looper.prepare();
//                    }
                    new Handler().post(runnable);//在子线程中直接去new 一个handler

                    Looper.loop();
                }
            }.start();
        } else {
            applicationContainer = findAttachForm();
            if (applicationContainer == null) {
                getActivity().finish();
                return;
            }
            addAttachForm(ll, applicationContainer);
        }

    }

    private ApplicationContainer generateOneForm(LinearLayout ll) {
        ApplicationContainer applicationContainer = null;
        String xmlName = stubObject.getString(EFXmlConstants.ATTR_FORM, "");
        String formName = xmlName.substring(0, xmlName.indexOf(".xml"));
        String formPath = EFAppAccountUtils.getAppAccountFormPath() + "/" + xmlName;
        try {
            InputStream inputStream = new FileInputStream(formPath);
            ViewSize viewSize = new ViewSize(ll.getMeasuredWidth(), ll.getMeasuredHeight());
            Form form = new Form();
            form.setFormName(formName);
            form.setInputStream(inputStream);
            form.setViewSize(viewSize);

            //生成单个表单
            ArrayList forms = new ArrayList();
            forms.add(form);
            applicationContainer = FormAppUtil.generateForm(forms, stubObject, EFAppAccountUtils.V8, new XML2Forms.FormCreationCompleteListener() {
                @Override
                public void onFormCreationComplete() {
//                    progressDialog.dismiss();
                    EFTitleView titleView = EFTitleViewUtils.getEFTitleView(EFAppAccountFormFragment.this);
                    if (titleView != null) {
                        titleView.dismissRightProgressBar();
                    }
                    handler.sendEmptyMessage(1);
                }
            });

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return applicationContainer;
    }

    private void addForm(LinearLayout ll, ApplicationContainer applicationContainer) {
        String xmlName = stubObject.getString(EFXmlConstants.ATTR_FORM, "");
        String formName = xmlName.substring(0, xmlName.indexOf(".xml"));
        FormApplication formApplication = applicationContainer.getFormApplication(formName);
        FormViewContainer formViewContainer = (FormViewContainer) formApplication.getFormContainer("form1");
        if (formViewContainer != null) {
            ll.removeAllViews();
            ll.addView(formViewContainer);
        }
    }

    private ApplicationContainer findAttachForm() {
        String menuParentID = stubObject.getString(EFAppAccountRegistry.ATTR_PARENT_ID, "");
        String parentID = menuParentID.substring("menu_".length());
//            StubObject parentStub = EFAppAccountRegistry.getStubByID(parentID);
//            String parentID = (String) parentStub.getID();
        ApplicationContainer applicationContainer = EFAppAccountUtils.applicationContainerMap.get(parentID);
        return applicationContainer;
    }

    private void addAttachForm(LinearLayout ll, ApplicationContainer applicationContainer) {
        String attachForm = stubObject.getString(EFXmlConstants.ATTR_ATTACH_FORM, "");
        String attachFormName = attachForm.substring(0, attachForm.indexOf(".xml"));
        FormApplication formApplication = applicationContainer.getFormApplication(attachFormName);
        if (formApplication != null) {
            FormViewContainer formViewContainer = (FormViewContainer) formApplication.getFormContainer("form1");
            if (formViewContainer == null) {
                Log.e("ee", "没有找到名称为form1的表单");
                return;
            }
            ViewGroup parent = (ViewGroup) formViewContainer.getParent();
            if (parent != null) {
                parent.removeView(formViewContainer);
            }

            ll.removeAllViews();
            ll.addView(formViewContainer);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.w("--", TAG + "------onDestroy");
    }
}
